package com.szcf.testserial.utils;


public class HexUtils {
	
    /**
     * getIpAddress()获得十进制，将十进制转化成二进制，每八位进行分割，将得到四组IP值
     * @param i
     * @return
     */
    public static String intToIp(int i) {
    	return (i & 0xFF) + "." +
    	((i >> 8) & 0xFF) + "." +
    	((i >> 16) & 0xFF) + "." +
    	((i >> 24) & 0xFF);    	
    }
    
    /**
     * 高4位
     * @param data
     * @return
     */
    public static int byteToHigh(byte data) {
    	return ((data & 0xf0) >> 4);
    }
    
    /**
     * 低4位
     * @param data
     * @return
     */
    public static int byteToLow(byte data) {
    	return (data & 0x0f);
    }
    
    /**
     * 获取验证的高低4位
     * @param hex
     * @return
     */
    public static String hexForHighLow(String hex) {
    	byte[] data = HexUtils.hexStringToBytes(hex);
		byte result = 0;
		for (int i = 0; i < data.length; i++) {
			result += (byte)data[i];
		}		
		return hex+String.format("%02X", byteToLow(result))+String.format("%02X", byteToHigh(result));
    }
    
    /**
     * 十六进制字符串转换成byte数组
     * @param hex
     * @return
     */
    public static byte[] hexStringToBytes(String hex) {
    	int length = hex.length()/2;
    	byte[] buffer = new byte[length];
    	int index = 0;
    	for (int i = 0; i < length; i++) {
    		buffer[i] = (byte) Integer.parseInt(hex.substring(index, index+2), 16);
    		index += 2;
    	}
    	
    	return buffer;
    }
}
